package blog

import (
	"time"

	"gitee.com/lishixi/gops/vblog/apps/utils"
	"github.com/go-playground/validator/v10"
	"github.com/infraboard/mcube/v2/exception"
	"github.com/infraboard/mcube/v2/tools/pretty"
)

var v = validator.New()

func NewBlogSet() *BlogSet {
	return &BlogSet{
		Items: []*Blog{},
	}
}

type BlogSet struct {
	Total int64   `json:"total"`
	Items []*Blog `json:"items"`
}

func NewBlog(in *CreateBlogRequest) (*Blog, error) {
	// 校验参数
	if err := in.Validate(); err != nil {
		return nil, exception.NewBadRequest("参数异常 %s", err)
	}

	return &Blog{
		ResourceMetaData:  *utils.NewResourceMetaData(),
		CreateBlogRequest: *in,
	}, nil
}

type Blog struct {
	// 对象元数据
	utils.ResourceMetaData
	// 创建的具体信息
	CreateBlogRequest
	// 文章状态
	Status
}

func (b *Blog) String() string {
	return pretty.ToJSON(b)
}
func (b *Blog) TableName() string {
	return "blogs"
}

type CreateBlogRequest struct {
	// 标题，可能要做模糊查询所以不设主键
	Title string `json:"title" gorm:"column:title;type:varchar(200)" validate:"required"`
	// 摘要
	Summary string `json:"summary" gorm:"column:summary;type:text" validate:"required"`
	// 内容
	Content string `json:"content" gorm:"column:content;type:text" validate:"required"`
	// 分类
	Category string `json:"category" gorm:"column:category;type:varchar(200);index" validate:"required"`
	// 标签
	Tags map[string]string `json:"tags" gorm:"column:tags;serializer:json"`
}

func (t *CreateBlogRequest) Validate() error {
	return v.Struct(t)
}

type Status struct {
	StatusSpec
	// 状态变更时间，主要拿发布时间
	ChangeAt *time.Time `json:"change_at" gorm:"change_at:title"`
}
type StatusSpec struct {
	// 0 草稿， 1 已发布， 2 审核...
	Stage STAGE `json:"stage" gorm:"column:stage;type:varchar(1);index"`
}
